import classNames from "classnames";
import React, {
  FocusEvent,
  KeyboardEvent,
  useImperativeHandle,
  useRef,
  useState,
} from "react";

export interface RefInputProps {
  focus: () => void;
  blur: () => void;
  input: (v: string) => void;
}

interface InputProps {
  value: string;
  maxLength?: number;
  className?: string;
  onInput?: (v: string) => void;
  onBlur?: (e: FocusEvent<HTMLInputElement>) => void;
  onPressEnter?: (e: KeyboardEvent<HTMLInputElement>) => void;
}

function Input(props: InputProps, ref?: React.Ref<RefInputProps>) {
  const { maxLength, value, onInput, onPressEnter, onBlur, className } = props;
  const [innerValue, setInnerValue] = useState(value);

  const inputRef = useRef<HTMLInputElement>(null);

  const handleInput = (e: any) => {
    const v = e.target.value as string;
    setInnerValue(v);
    onInput?.(v);
  };

  const handleKeyUp = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key == "Enter") onPressEnter?.(e);
  };

  const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
    onBlur?.(e);
  };

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    blur: () => inputRef.current?.blur(),
    input: (v: string) => setInnerValue(v),
  }));

  return (
    <input
      ref={inputRef}
      maxLength={maxLength}
      value={innerValue}
      onInput={handleInput}
      onKeyUp={handleKeyUp}
      onBlur={handleBlur}
      className={classNames("ct0-tag-select-input", className)}
    ></input>
  );
}

export default React.forwardRef(Input);
